import React from "react";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import {
  Button,
  Form,
  Input,
  // Space,
  Modal,
  Alert,
  Select,
  InputNumber,
  message,
} from "antd";
import { useState } from "react";
import { req } from "@/common/methods";
import Loading from "@/components/Loading/index.tsx";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

import styles from "./index.module.scss";

let timer: number | undefined = undefined;

const Inventory: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [baseData, setBaseData] = useState<any>({});
  const fetchBaseData = () => {
    setLoading(true);
    req("/api/goods/easy_get")
      .then((data: any) => {
        setBaseData({ ...data });
        setLoading(false);
      })
      .catch((error) =>
        Modal.error({
          title: "错误",
          content: <>初始化数据失败,{error}</>,
        })
      );
  };
  useEffect(() => fetchBaseData(), []);
  const [form] = Form.useForm();
  const [goodsInputData, setGoodsInputData] = useState<any>({});
  const handleGoodsSearch = (search: string, key: string | number) => {
    clearTimeout(timer);
    timer = window.setTimeout(() => {
      req("/api/goods/get_all", { search }, "get")
        .then((data: any) => {
          setGoodsInputData({
            ...{ goodsInputData },
            [key]: data.map((item: any) => ({
              label: item.name,
              value: item.id,
            })),
          });
          //console.log(data);
        })
        .catch((error) => {
          message.error("错误：" + error);
        });
    }, 500);
    //
  };
  const handleGoodsChange = (values: string, key: string | number) => {
    //console.log(values);
    console.log("baseData", baseData);
    const currentFieldsValue = { ...(form as any).getFieldValue() };
    currentFieldsValue.inventory[key] = {
      ...currentFieldsValue.inventory[key],
      unit: baseData[values].unit,
      specs: baseData[values].specs,
      count: baseData[values].count,
      input_count: baseData[values].count,
      //input_count:currentFieldsValue.inventory[key].count || baseData[values].count,
    };
    currentFieldsValue.inventory[key].change_count =
      currentFieldsValue.inventory[key].input_count -
      currentFieldsValue.inventory[key].count;
    console.log(currentFieldsValue);
    form.setFieldsValue({ ...currentFieldsValue });
  };
  const [isSubmitButtonDisabled, setSubmitButtonDisabled] = useState(false);
  const onFinish = (values: any) => {
    setSubmitButtonDisabled(true);
    //console.log(values);
    try {
      if (
        typeof values !== "object" ||
        !values ||
        typeof values.inventory !== "object" ||
        !values.inventory ||
        !Array.isArray(values.inventory)
      ) {
        throw "错误的数据类型" + JSON.stringify({ 数据: values }, null, 2);
        return;
      }
      if (values.inventory.length === 0) {
        throw "当前清单为0，无法提交";
        return;
      }
      //检查数据重复
      const ids = values.inventory.map((item: any) => item.goods_id);
      ids.forEach((item1: any, index1: number) => {
        if (ids.indexOf(item1) !== index1) {
          throw "有重复的数据，无法提交，请检查";
          return;
        }
      });
      const query = (() => {
        const res = values.inventory.map((item: any) => {
          return {
            method: 30,
            goods_id: item.goods_id,
            change_count: item.change_count,
            reason: item.reason,
            remark: "[" + item.reason + "]" + (item.remark || ""),
          };
        });
        return res;
      })();
      console.log(query);
      req("/api/storage", { data: JSON.stringify(query) }, "post")
        .then((data: any) => {
          Modal.success({
            title: "提交成功",
            content: (
              <>
                盘点数据已成功提交，库存已更新，请留意。
                <pre style={{ visibility: "hidden" }}>{"" + data}</pre>
              </>
            ),
            onOk() {
              navigate(`/management/lib/goods`);
            },
          });
        })
        .catch((error) => {
          Modal.error({
            title: "提交失败",
            content: <>盘点数据提交失败，{"" + error}</>,
          });
          setSubmitButtonDisabled(false);
        });
    } catch (e) {
      Modal.error({
        title: "数据初始化错误",
        content: <>数据校验出现错误,{"" + e}</>,
        onOk() {
          setSubmitButtonDisabled(false);
        },
        onCancel() {
          setSubmitButtonDisabled(false);
        },
      });
    }
    /*
    Modal.info({
        title:'提交',
        content:<>{'Received values of form:' +  JSON.stringify(values)}</>
    });
    */
  };
  const onFinishFailed = (error: any) => {
    Modal.error({
      title: "提交失败",
      content: (
        <>
          您录入的数据未能正常提交，请检查，
          {typeof error === "object" ? JSON.stringify(error || {}) : "" + error}
        </>
      ),
    });
  };
  return (
    <>
      {loading ? (
        <Loading />
      ) : (
        <Form
          name="dynamic_form_nest_item"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{ maxWidth: "100%" }}
          autoComplete="off"
          form={form}
        >
          <Form.List name="inventory">
            {(fields, { add, remove }) => (
              <>
                {false && (
                  <Alert
                    message="功能还在开发中……"
                    type="error"
                    showIcon
                    closable
                  ></Alert>
                )}
                {fields.map(({ key, name, ...restField }) => (
                  <div
                    key={key}
                    style={{ display: "flex", gap: "8px", marginBottom: 8 }}
                    // align=""
                  >
                    <Form.Item
                      {...restField}
                      name={[name, "goods_id"]}
                      label="物品名称"
                      rules={[{ required: true, message: "物品不能为空" }]}
                      style={{ flex: "1", minWidth: "200px" }}
                    >
                      {/* <Select placeholder="First Name" /> */}
                      <Select
                        showSearch
                        placeholder="选择物品"
                        //optionFilterProp="children"
                        //filterOption={(input,option) => }
                        options={goodsInputData[name]}
                        onChange={(values) => handleGoodsChange(values, name)}
                        onSearch={(search) => handleGoodsSearch(search, name)}
                        defaultActiveFirstOption={true}
                        suffixIcon={null}
                        filterOption={false}
                      />
                    </Form.Item>
                    {/* <Form.Item label="物品" name={[subField.name, 'goods_id']}  rules={[{required:true,message:'物品不能为空'}]}>
                    <Select
                      showSearch
                      placeholder="选择物品"
                      optionFilterProp="children"
                      //onChange={onChange}
                      //onSearch={onSearch}
                      filterOption={(input: string, option: { label: string; value: string }) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                      //options={baseDataToOpt(baseData)}
                      options={goodsInputData}
                      onChange={(values) => handleGoodsChange(values,subField.key)}
                      onSearch={handleGoodsSearch}
                      defaultActiveFirstOption={true}
                      suffixIcon={null}
                      filterOption={false}
                    />
                  </Form.Item> */}
                    <Form.Item
                      {...restField}
                      name={[name, "specs"]}
                      label="规格"
                      style={{ width: "150px" }}
                    >
                      <Input placeholder="规格" disabled />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "unit"]}
                      label="单位"
                      style={{ width: "120px" }}
                    >
                      <Input placeholder="单位" disabled />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "count"]}
                      label="账存"
                      style={{ width: "120px" }}
                    >
                      <InputNumber placeholder="账存" disabled />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "input_count"]}
                      label="实存"
                      rules={[{ required: true, message: "请输入实存数量" }]}
                      style={{ width: "150px" }}
                    >
                      <InputNumber
                        placeholder="实存"
                        onChange={(value) => {
                          value;
                          const fieldsValue = { ...form.getFieldsValue() };
                          fieldsValue.inventory[name].change_count =
                            fieldsValue.inventory[name].input_count -
                              fieldsValue.inventory[name].count || 0;
                          form.setFieldsValue({ ...fieldsValue });
                        }}
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "change_count"]}
                      label="损溢"
                      style={{ width: "120px" }}
                    >
                      <InputNumber
                        placeholder="损溢"
                        readOnly
                        status="warning"
                        style={{
                          backgroundColor: (() => {
                            let res = "lightgray";
                            if (form.getFieldsValue().inventory) {
                              if (form.getFieldsValue().inventory[name]) {
                                if (
                                  form.getFieldsValue().inventory[name]
                                    .change_count
                                ) {
                                  if (
                                    form.getFieldsValue().inventory[name]
                                      .change_count > 0
                                  ) {
                                    res = "#aaffaa";
                                  } else {
                                    res = "#ffaaaa";
                                  }
                                }
                              }
                            }
                            return res;
                            //form.getFieldsValue().inventory[name].change_count > 0 ? '#aaffaa' :'#ffaaaa'
                          })(),
                        }}
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "reason"]}
                      label="事由"
                      initialValue="盘盈/盘亏"
                      rules={[{ required: true, message: "请选择事由" }]}
                      style={{ flex: 1 }}
                    >
                      {/* <Input placeholder="请选择事由" /> */}
                      <Select
                        options={[
                          { label: "日常盘点", value: "日常盘点" },
                          {
                            label: "物品损坏导致亏损",
                            value: "物品损坏导致亏损",
                          },
                          { label: "调整库存", value: "调整库存" },
                          { label: "记录出错", value: "记录出错" },
                          { label: "系统问题", value: "系统问题" },
                        ]}
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, "remark"]}
                      label="备注"
                      //rules={[{ required: true, message: '请填写备注' }]}
                      style={{ flex: 1, minWidth: "200px" }}
                    >
                      <Input placeholder="请填写备注" />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </div>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    增加项目
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
          <div className={styles["submit-btn-area"]}>
            <Form.Item>
              <Button
                className={styles["submit-btn"]}
                type="primary"
                htmlType="submit"
                disabled={isSubmitButtonDisabled}
              >
                提交盘点
              </Button>
            </Form.Item>
          </div>
        </Form>
      )}
    </>
  );
};

export default Inventory;
